package com.yihu.wlyy.web.patient.followup;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.follow.FollowUpItemRecord;
import com.yihu.wlyy.entity.follow.FollowUpItemRecordAnswer;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import com.yihu.wlyy.web.patient.followup.vo.FollowUpItemRecordAnswerVO;
import com.yihu.wlyy.web.patient.followup.vo.FollowUpItemRecordDetailVO;
import com.yihu.wlyy.web.patient.followup.vo.FollowUpItemRecordQuestionOptionVO;
import com.yihu.wlyy.web.patient.followup.vo.FollowUpItemRecordQuestionVO;
import com.yihu.wlyy.web.patient.followup.vo.FollowupPlanVO;

/**
 * 患者端：随访干预
 * 
 * @author cwd
 * 
 */
@Controller
@RequestMapping(value = "/patient/followup")
public class PatientFollowUpController extends BaseController {
	@Autowired
	private PatientFollowUpService patientFollowUpService;
	/**
	 * 主页-随访计划列表
	 * 
	 * @param pagesize
	 *            每页显示条数   /patient/followup/followupPlanList
	 * @param pagenum
	 *            当前页
	 * @return
	 */
	@RequestMapping(value = "followupPlanList")
	@ResponseBody
	public String followupPlanList(
			@RequestParam("id")long id, 
			@RequestParam("pagesize")int pagesize, 
			@RequestParam(value="title",required=false)String title) {
		try {
			String userId = super.getUID();
			List<FollowupPlanVO> followupPlanVOs = patientFollowUpService
					.followupPlanList(userId, id, pagesize, title);
			JSONArray array = new JSONArray();
			for (FollowupPlanVO followupPlanVO : followupPlanVOs) {
				JSONObject jo = new JSONObject();
				// 添加計劃
				jo.put("title", followupPlanVO.getTitle());
				// 添加日期
				jo.put("czrq", DateUtil.dateToStrShort(followupPlanVO.getCzrq()));
				// 添加code
				jo.put("code", followupPlanVO.getCode());
				// 添加狀態
				jo.put("status", followupPlanVO.getStatus());
				jo.put("id", followupPlanVO.getId());
				// 添加狀態  -1暂停，0进行中，1已结束
				switch (followupPlanVO.getStatus()) {
				case -1:
					jo.put("statusName", "暂停");
					break;
				case 0:
					jo.put("statusName", "进行中");
					break;
				case 1:
					jo.put("statusName", "已结束");
					break;
				}
				// 添加名称
				jo.put("doctorName", followupPlanVO.getDoctorName());
				jo.put("photo", followupPlanVO.getDoctorPhoto());
				array.put(jo);
			}
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}
	/**
	 * 主页-随访计划-根据计划code查找随访项
	 * 
	 * @param planCode
	 * @param title
	 * @return
	 */
	@RequestMapping(value = "getFollowUpPlanStageItemListByParam")
	@ResponseBody
	public String getFollowUpPlanStageItemListByParam(
			@RequestParam(value="planCode",required=false) String planCode,
			@RequestParam(value="type",required=false) String type,
			@RequestParam(value="title",required=false)String title) {
		try {
			JSONArray array = new JSONArray();
			String uid=super.getUID();
			List<FollowUpItemRecord> followupPlanVOs = patientFollowUpService
					.getFollowUpPlanStageItemListByPlanCode(uid,planCode,title,type);
			for (FollowUpItemRecord followUpItemRecord : followupPlanVOs) {
				JSONObject jo = new JSONObject();
				// 添加計劃
				jo.put("title", followUpItemRecord.getTitle());
				
				jo.put("id", followUpItemRecord.getId());
				// 添加日期
				jo.put("czrq", DateUtil.dateToStrShort(followUpItemRecord.getCzrq()));
				// 添加code
				jo.put("code", followUpItemRecord.getCode());
				// 添加item
				jo.put("itemCode", followUpItemRecord.getItem());
				//类型
				jo.put("type", followUpItemRecord.getType());
				// 添加狀態
				jo.put("status", followUpItemRecord.getStatus());
				// 添加狀態  0进行中，1已结束
				if(followUpItemRecord.getStatus()==0){
					jo.put("statusName", "进行中");
				}else{
					jo.put("statusName", "已结束");
				}
				array.put(jo);
			}
			
			return write(200, "查询成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 主页-随访计划-查看单个随访周期的详细信息
	 * 
	 * @param recoredCode
	 * @return
	 */
	@RequestMapping(value = "followupPlanListLeftDetail")
	@ResponseBody
	public String followupPlanListLeftDetail(String recoredCode) {
		try {
			String userId = super.getUID();
			FollowUpItemRecordDetailVO followUpItemRecordDetailVO = patientFollowUpService
					.getFollowUpItemRecordDetailById(recoredCode);

			JSONObject jo = new JSONObject();
			jo.put("title", followUpItemRecordDetailVO.getTitle());
			jo.put("id", followUpItemRecordDetailVO.getId());
			jo.put("plan", followUpItemRecordDetailVO.getPlan());
			jo.put("stage", followUpItemRecordDetailVO.getStage());
			jo.put("item", followUpItemRecordDetailVO.getItem());
			jo.put("code", followUpItemRecordDetailVO.getCode());
			jo.put("czrq", DateUtil.dateToStrShort(followUpItemRecordDetailVO.getCzrq()));
			jo.put("type", followUpItemRecordDetailVO.getType());
			switch (followUpItemRecordDetailVO.getType()) {
			case 1:
				jo.put("typeName", "问卷");
				break;
			case 2:
				jo.put("typeName", "体侧");
				break;
			}
			jo.put("status", followUpItemRecordDetailVO.getStatus());
			if(followUpItemRecordDetailVO.getStatus()==0){
				jo.put("statusName", "进行中");
			}else{
				jo.put("statusName", "已完成");
			}
			jo.put("doctor", followUpItemRecordDetailVO.getDoctor());
			jo.put("doctorName", followUpItemRecordDetailVO.getDoctorName());
			JSONArray array = new JSONArray();
			// 遍历所有问题
			for (FollowUpItemRecordQuestionVO followUpItemRecordQuestionVO : followUpItemRecordDetailVO
					.getFollowUpItemRecordQuestionVO()) {
				JSONObject joTemp = new JSONObject();
				// 设置问题
				joTemp.put("title", followUpItemRecordQuestionVO.getTitle());
				joTemp.put("plan", followUpItemRecordQuestionVO.getPlan());
				joTemp.put("stage", followUpItemRecordQuestionVO.getStage());
				joTemp.put("item", followUpItemRecordQuestionVO.getItem());
				joTemp.put("record", followUpItemRecordQuestionVO.getRecord());
				joTemp.put("code", followUpItemRecordQuestionVO.getCode());
				joTemp.put("type", followUpItemRecordQuestionVO.getType());
				//1单选，2多选，3问答
				switch (followUpItemRecordDetailVO.getType()) {
				case 1:
					jo.put("typeName", "单选");
					break;
				case 2:
					jo.put("typeName", "多选");
					break;
				case 3:
					jo.put("typeName", "问答");
					break;
				}
				//1血糖，2血压，3体重，4腰围
				joTemp.put("index", followUpItemRecordQuestionVO.getIndex());
				switch (followUpItemRecordDetailVO.getStatus()) {
				case 1:
					jo.put("indexName", "血糖");
					break;
				case 2:
					jo.put("indexName", "血压");
					break;
				case 3:
					jo.put("indexName", "体重");
					break;
				case 4:
					jo.put("indexName", "腰围");
					break;
				}
				// 设置问题的选项
				JSONArray option = new JSONArray();
				for (FollowUpItemRecordQuestionOptionVO followUpItemRecordQuestionOptionVO : followUpItemRecordQuestionVO
						.getFollowUpItemRecordQuestionOptions()) {
					JSONObject optionJO = new JSONObject();
					optionJO.put("plan", followUpItemRecordQuestionOptionVO.getPlan());
					optionJO.put("stage", followUpItemRecordQuestionOptionVO.getStage());
					optionJO.put("item", followUpItemRecordQuestionOptionVO.getItem());
					optionJO.put("record", followUpItemRecordQuestionOptionVO.getRecord());
					optionJO.put("question",followUpItemRecordQuestionOptionVO.getQuestion());
					optionJO.put("code",followUpItemRecordQuestionOptionVO.getCode());
					optionJO.put("des",followUpItemRecordQuestionOptionVO.getDes());
					option.put(optionJO);
				}
				joTemp.put("option", option);
				// 设置问题的答案
				// 如果已经回答 设置答案
				JSONArray answer = new JSONArray();
				for(FollowUpItemRecordAnswerVO followUpItemRecordAnswerVO:followUpItemRecordQuestionVO.getFollowUpItemRecordAnswerVOs()){
					JSONObject answerJO = new JSONObject();
					answerJO.put("answer",followUpItemRecordAnswerVO.getAnswer());
					answerJO.put("option",followUpItemRecordAnswerVO.getOption());
					answerJO.put("plan", followUpItemRecordAnswerVO.getPlan());
					answerJO.put("stage", followUpItemRecordAnswerVO.getStage());
					answerJO.put("item", followUpItemRecordAnswerVO.getItem());
					answerJO.put("type", followUpItemRecordAnswerVO.getType());//1单选，2多选，3问答
					switch (followUpItemRecordDetailVO.getStatus()) {
						case 1:
							jo.put("typeName", "单选");
							break;
						case 2:
							jo.put("typeName", "多选");
							break;
						case 3:
							jo.put("typeName", "问答");
							break;
						}
					answerJO.put("record", followUpItemRecordAnswerVO.getRecord());
					answerJO.put("question",followUpItemRecordAnswerVO.getQuestion());
					answerJO.put("index",followUpItemRecordAnswerVO.getIndex());
					switch (followUpItemRecordDetailVO.getStatus()) {
						case 1:
							jo.put("indexName", "血糖");
							break;
						case 2:
							jo.put("indexName", "血压");
							break;
						case 3:
							jo.put("indexName", "体重");
							break;
						case 4:
							jo.put("indexName", "腰围");
							break;
						}
					answerJO.put("doctor", followUpItemRecordAnswerVO.getDoctor());
					answerJO.put("doctorName", followUpItemRecordAnswerVO.getDoctorName());
					answer.put(answerJO);
				}
				joTemp.put("answer", answer);
			array.put(joTemp);
			}
			jo.put("question", array);
			return write(200, "查询成功!", "data", jo);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 主页-随访计划-保存单个随访周期的答案
	 * 
	 * @return
	@RequestMapping(value = "saveFollowUpItemRecordAnswer")
	@ResponseBody
	public String saveFollowUpItemRecordAnswer(int type,String jsonData) {
		try {
			String userId = super.getUID();
			
			JSONArray array = new JSONArray();
			
			return write(200, "保存成功!");
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}
	 */



	/**
	 * 完成情况
	 * {
	 * 		doctorName:"医生姓名“,
	 *      czrq:" yyyy-MM-dd",
	 *      title："标题"
	 *      wjAmount:"总问卷随访数",
	 *      wjFinishAmount:"已完成问卷随访数",
	 *      tcAmount:"总体测随访数",
	 *      tcFinishAmount:"已完成体测随访数",
	 *      planCode:"",
	 *      docSummary:[
	 *                {
	 *                  summary:"医生总结",
	 *                  doctorName:"医生名字",
	 *                  czrq:"完成时间",
	 *                  photo:"",
	 *                  type:"1、计划  2、阶段 3、随访项 4、随访纪录",
	 *                  typeName:"",
	 *                }
	 *             ]
	 * }
	 * @param id
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "getPlanDetail")
	@ResponseBody
	public String getPlanDetail(
			@RequestParam("planCode") String planCode) {
		try {
			JSONObject jo=patientFollowUpService.getPlanDetail(planCode);
			return write(200, "查询成功!", "list", jo);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 完成情况-问卷详情
	 * 
	 * @param itemCode
	 * @return
	 *  *{
		    "msg": "查询成功!",
		    "data": {
		        "question": [ {
		                "answer": [{
		                        "czrq": "2016-05-31",
		                        "desc": [
		                            "胃散",
		                            "泻立停"
		                        ] }
		                ],
		                "title": "吃了什么药"
		            },
		            {
		                "answer": [],
		                "title": "体征检测"
		            },
		    },
		    "status": 200
		}
	 */
	@RequestMapping(value = "getFollowUpWJs")
	@ResponseBody
	public String getFollowUpWJs(
			@RequestParam("itemCode") String itemCode) {
		try {
			JSONObject jo=patientFollowUpService.getFollowUpWJs(itemCode);
			return write(200, "查询成功!", "data", jo);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}


	/**
	 * 完成情况-医生小结
	 * 
	 * @param planCode
	 * @return
	 * 
	 * {
	 *    title:"",
		  summary:[{
		   summary:"总结“,
		   czrq:"yyyy-mm-dd",
		   title:"标题",
		   doctorName:"医生名字"
		   photo:"",
		   id:""
		  }]
	 * }
	 * 
	 *
	 */
	@RequestMapping(value = "getItemDetail")
	@ResponseBody
	public String getItemDetail(
			@RequestParam("id")long id, 
			@RequestParam("pagesize")int pagesize, 
			@RequestParam("itemCode") String itemCode) {
		try {
			JSONObject jo=patientFollowUpService.getItemDetail(id,pagesize,itemCode);
			return write(200, "查询成功!", "data", jo);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}
	
	/**
	 * 随访保存
	 * 
	 * @param answers 随访答案JSON
	 * @return
	 */
	@RequestMapping(value = "/saveRecordAnswers")
	@ResponseBody
	public String saveRecordAnswers(String answers){
		try{
			ObjectMapper mapper = new ObjectMapper();
			FollowUpItemRecordAnswer[] answerArray = mapper.readValue(answers, FollowUpItemRecordAnswer[].class);
			
			for(FollowUpItemRecordAnswer answer : answerArray){
				answer.setCzrq(new Date());
			}
			
			patientFollowUpService.saveRecordAnswers(Arrays.asList(answerArray));
			
			return success("提交成功！");
		}
		catch(Exception e){
			error(e);
			return error(-1, "提交失败 ！");
		}
	}
	
	/**
	 * 完成情况-体征详情
	 * 1血糖，2血压，3体重，4腰围
	 * @param itemCode
	 * @return
	 *   "msg":"查询成功!",
		    "data":{
		        "title":"血压（舒张压）",
		        "datas":[
		            [
		                {
		                    "answer":"80",
		                    "czrq":"2016-05-31"
		                },
		                {
		                    "answer":"220",
		                    "czrq":"2016-05-31"
		                }
		            ]
		        ]
		    },
		    "status":200
		}
	 */
	@RequestMapping(value = "getFollowUpTZs")
	@ResponseBody
	public String getFollowUpTZs(
			@RequestParam("question") String question) {
		try {
			JSONObject jo=patientFollowUpService.getFollowUpTZs(question);
			return write(200, "查询成功!", "data", jo);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}
	/**
	 * 
	 * @param itemCode  目前沒用的接口
	 * @return
	 *  [{
	 *    itemCode:"",
	 *    index:"",
	 *    indexName:""
	 * },{
	 *    itemCode:"",
	 *    index:"",
	 *    indexName:""
	 * }]
	 */
	@RequestMapping(value = "getTypeList")
	@ResponseBody
	public String getTypeList(
			@RequestParam("itemCode") String itemCode) {
		try {
			JSONArray jo=patientFollowUpService.getTypeList(itemCode);
			return write(200, "查询成功!", "list", jo);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}
	
	/**
	 * 
	 * @param itemCode
	 * @return
	 *  [{
	 *    title:"",
	 *    question:""
	 * },{
	 *    title:"",
	 *    question:""
	 * }]
	 */
	@RequestMapping(value = "getQuestionList")
	@ResponseBody
	public String getQuestionList(
			@RequestParam("itemCode") String itemCode) {
		try {
			JSONArray jo=patientFollowUpService.getQuestionList(itemCode);
			return write(200, "查询成功!", "list", jo);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}
	/**
	 * 
	 * @param planCode
	 * @param type
	 * @return
	 * {
	 *    title:"",
	 *    item:[{
	 *       title:"",
	 *       item:"",
	 *       plan:"",
	 *       stage:"",
	 *    }]
	 * 
	 * }
	 */
	@RequestMapping(value = "getItemList")
	@ResponseBody
	public String getItemList(
			@RequestParam("planCode") String planCode,
			@RequestParam("type") int type) {
		try {
			JSONObject jo=patientFollowUpService.getItemList(planCode,type);
			return write(200, "查询成功!", "data", jo);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}
	
}
